<template>
    <div >
        <div class="zuidaBox" >
            <div v class="box">
                <div class="flex align_center" style="margin-bottom: 1.5%;padding-left: 24px;">
                    <div class="flex align_center" style="margin-right: 40px;">
                        <div >付款人：</div>
                        <a-select  v-model="objcetData.pay_dept_id" style="width:390px;" :filter-option="filterOption"
                        :options="dept_list" :field-names="{ value: 'id', label: 'name' }" allow-clear allow-search
                        placeholder="请选择公司" @change="handleSelectPay_dept_id($event)" />
                    </div>
                </div>
                <a-table :columns="tablecolumnsts" :data="objcetData.detail" :pagination='false' :span-method="spanMethodAll" :bordered="{wrapper: true, cell: true}">
                    <template #price_type="{record,rowIndex}">
                        <div v-if="record.type == 1">
                            <a-select  v-model="record.price_type" style="flex:1" :filter-option="filterOption"
                            :options="price_typeList" :field-names="{ value: 'key', label: 'title' }" allow-clear allow-search
                            placeholder="计费类型" @change="handleSelect($event,rowIndex)" />
                        </div>
                        <div v-if="record.type == 2">
                            <a-link @click="handleAdd(rowIndex,1)"><icon-plus /> 添加费用项</a-link>
                        </div>
                    </template>
                    <template #no_tax_price="{record}">
                        <div v-if="record.price_type && record.pay_real_price">{{ (record.no_tax_price - 0).toFixed(2)  }}</div>
                        <div v-else></div>
                    </template>
                    <template #tax_price="{record}">
                        <div v-if="record.price_type && record.pay_real_price">{{ (record.tax_price - 0).toFixed(2)  }}</div>
                        <div v-else></div>
                    </template>
                    <template #pay_name="{record}">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.pay_name"  placeholder="项目名称" allow-clear />
                        </div>
                    </template>
                    <template #pay_price="{record}">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.pay_price"  placeholder="原金额" allow-clear />
                        </div>
                    </template>
                    <template #pay_real_price="{record,rowIndex}">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.pay_real_price"  placeholder="实际金额" allow-clear @input="handleInput($event,rowIndex)" />
                        </div>
                        <div v-if="record.type == 2">
                            {{handleZongPrice(2)}}
                        </div>
                    </template>
                    <template #remark="{record}">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.remark"  placeholder="备注" allow-clear />
                        </div>
                    </template>
                    <template #caozuo="{record,rowIndex}">
                        <div v-if="record.type == 1">
                            <a-link @click="handleAdd(rowIndex,2)">删除</a-link>
                        </div>
                    </template>
                    
                </a-table>
            </div>
        </div>
        <div class=" flex align_center" style="padding: 10px 0 0;border-top: 1px solid rgba(0, 0, 0, .15);" >
            <div class="flex flex_1 justify_around">
                <!-- <div>不含税合计金额：{{handleZongPrice(3)}}</div>
                <div>税额合计金额：{{handleZongPrice(4)}}</div>
                <div>实际支付合计金额：{{handleZongPrice(2)}}</div> -->
            </div>
            <div class="flex" >
                <a-button style="margin-right: 20px;" @click="handleCel">取消支付</a-button>
                <!-- zhifuShow = true -->
                <a-popconfirm @ok="handleZhifu" content="是否确认选中的账单收费?确认后将生成一笔待支付账单">
                    <a-button type="primary" >确定选择</a-button>
                </a-popconfirm>
                
            </div>
        </div>
        
        <a-modal :mask-closable="false"  v-model:visible="zhifuShow" title="支付" @cancel="quxiaozhifu" ok-text="支付并打印收据" :width="600" :on-before-ok="handelzhifuOk">
                <div class="" style="margin-bottom: 2%;padding-left: 24px;height: 300px;">
                    <div class="flex align_center" style="margin-bottom: 2%;">
                        <div style="width: 80px;">结算方式：</div>
                        <a-radio-group v-model="jiesuan" :options="jiesuanOptions" />
                    </div>
                    <div v-if='jiesuan == "3"'>
                        <div style="display: flex;align-items: center;margin-bottom: 2%;">
                            <div style="width: 80px;">支付方式</div>
                            <a-radio-group v-model="zhifu" :options="zhifuOptions" />
                        </div>
                    </div>
                    <div v-if="jiesuan == '1'" style="margin-bottom: 2%;">
                        <div style="margin-bottom: 2%;">实际付款金额：{{handleZongPrice(2)}}元</div>
                        <div>当前可用余额：{{availableAmount}}元</div>
                    </div>
                    <div style="display: flex;align-items: center;margin-bottom: 2%;">
                        <div style="width: 80px;">支付时间</div>
                        <a-date-picker
                            style="width: 100%; "
                            show-time
                            v-model="pay_date"
                            format="YYYY-MM-DD HH:mm"
                        />
                    </div>
                </div>

        </a-modal>

        <!-- 打印派送单 -->
		<a-modal :mask-closable="false" 
			v-model:visible="shoujuShow"
			width="auto"
			title="打印收据"
			ok-text="打印"
            @cancel="quxiaoshouju"
			:footer="false"
		>
			<shouju :user="user" :row="shoujuItem"  v-if="shoujuShow"></shouju>
		</a-modal>
    </div>
</template>

<script setup>
    import { defineProps, defineEmits, ref, reactive, onMounted } from "vue";
    import FinancialPayOrder from "@/api/financial/financialPayOrder";
    import { request } from "@/utils/request.js";
    import commonApi from "@/api/common";
    import tool from '@/utils/tool'
    import { pinyin } from "pinyin-pro"
    import { Message } from "@arco-design/web-vue";
    import shouju from "@/components/shoukuan/index.vue"
    import { useUserStore } from "@/store";
    const userStore = useUserStore();
    const user = userStore.user;
    const shoujuShow = ref(false)
    const shoujuItem = ref({})
    const emit = defineEmits(['quxiao','shuaxin'])
    const props = defineProps({
        item: Object,
        type: Number,   //   type = 1 提货  type = 2 到货  type = 3 装车单
    })
    const pay_date = ref(tool.dateFormat(
			Math.round(new Date().getTime() / 1000).toString(),
			"yyyy-MM-dd hh:mm:ss"
		))
    const zongPrice = ref(0)
    const itemData = ref({
        page:1,
        pageSize:100,
        is_confirm:0,
    })
    const zhifu = ref('3')
    const jiesuan = ref('')
    const opening_bank = ref()
    const account = ref()
    const account_name = ref()
    const fileList = ref('')
    const zhifuOptions = ref([
        { label: '对公转账', value: '3' },
        { label: '现金', value: '2' },
        { label: '惠支付', value: '1' },
    ])
    const dept_list = ref([])
    const itemList = ref([])
    const price_typeList = ref([])    // 计费类型
    const zhifuShow = ref(false)
    const payOrderId = ref(0)
    const zhifuData = ref({
        prediction_id:'',
        pay_dept_id:'',
        pay_items_json:[],
    })
    const objcetData = ref({
        prediction_id:'',
        pay_dept_id:'',
        detail:[
            {
                car_nos:'',
                type:1,
                price_type:'',
                pay_name:'',
                no_tax_price:'',
                tax_price:'',
                pay_real_price:'',
                remark:'',
                caozuo:'',
            },{
                car_nos:'',
                type:2,
                price_type:'',
                pay_name:'',
                no_tax_price:'',
                tax_price:'',
                pay_real_price:'',
                remark:'',
                caozuo:'',
            }
        ]
    })
    const shuilvList = ref([])
    const filterOption = (v,option)=>{
        return option.keywords.some(keywords=>keywords.includes(v))
    }
    const jiesuanOptions = ref([
          {
            label: "现结",
            value: "3",
          },
          {
            label: "周期结算",
            value: "2",
          },
          {
            label: "预付款",
            value: "1",
          }
    ]) 

    const tablecolumnsts = [
        {
          title: '车号',
          dataIndex: 'car_nos',
          width:120,
          
        },
        {
          title: '计费类型',
          dataIndex: 'price_type',
          width:160,
          slotName:'price_type'
        },
        {
          title: '收费项目',
          dataIndex: 'pay_name',
          width:140,
          slotName:'pay_name'
        },
        // {
        //     title: '不含税金额',
        //     dataIndex: 'no_tax_price',
        //     width:110,
        //     slotName:'no_tax_price'
        // },
        // {
        //     title: '税额',
        //     dataIndex: 'tax_price',
        //     width:80,
        //     slotName:'tax_price'
        // },
        {
          title: '实际金额',
          dataIndex: 'pay_real_price',
          width:120,
          slotName:'pay_real_price'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width:140,
          slotName:'remark'
        },
        {
          title: '操作',
          dataIndex: 'caozuo',
          slotName:'caozuo',
          width:80,
        },
    ];
    const handleSelect = (e,indexs)=>{
        price_typeList.value.map((v, i) => {
            if (v.key == e) {
                objcetData.value.detail[indexs].pay_name = v.title
            }
        })
    }
    const handleInput = (e,indexs)=>{
        if(objcetData.value.detail[indexs].price_type != ''){
            gethandleShuilv(indexs) 
        }
    }
    const availableAmount = ref(0)
    const quxiaoshouju = ()=>{
        emit("shuaxin")
    }
    onMounted(()=>{
        console.log(props.item)
        objcetData.value.detail.map((v,i)=>{
            v.car_nos = props.item.car_no
        })
        zhifuData.value.prediction_id = props.item.id
        objcetData.value.pay_dept_id = props.item.dept_id
        handelavailableAmount(objcetData.value.pay_dept_id)
        objcetData.value.detail = handleWeizhi(objcetData.value.detail)
        handleDeptList()
        commonApi.getDict("price_type").then((res) => {
            res.data.map((v,i)=>{
                v.keywords = [
                    v.title,
                    pinyin(v.title,{toneType:'none',pattern:'first'}).split(' ').join(''),
                    pinyin(v.title,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
                ]
            })
            price_typeList.value = res.data;
        });
    })
    const gethandleShuilv = (indexs)=>{
        request({
            url: "financial/payOrder/get_tax_price",
            method: "post",
            data: {
                price_type:objcetData.value.detail[indexs].price_type,
                price:objcetData.value.detail[indexs].pay_real_price,
            },
        }).then((res) => {
            console.log(res)
            objcetData.value.detail[indexs].no_tax_price = res.data.no_tax_price
            objcetData.value.detail[indexs].tax_price = res.data.tax_price
        });
    }
    const getaccount = () =>{
        request({
            url: "system/dataDict/index",
            method: "get",
            params: {
            page:1,
                pageSize:10,
                type_id:41
            },
        }).then((res) => {
            opening_bank.value = res.data.items[0].value
            account.value = res.data.items[1].value
            account_name.value = res.data.items[2].value
        });
    }
    const handleConsole = ()=>{
        console.log(itemList.value)
    }
    const handleCel = () =>{  // 取消支付
        emit('quxiao')
    }
    const quxiaozhifu = ()=>{
        zhifuShow.value = false
        emit('quxiao')
    }
    const handleZhifu = ()=>{
        let arr = []
        let err = 0    //  错误提示   1 没有选择付款人  2 实际金额为空或为负数  3 计费类型  4 收费项目  5 原金额  6 请选择账单
        objcetData.value.detail.map((vv,ii)=>{
            if((vv.type == 0) && vv.is_confirm == 1){
                if(vv.pay_real_price == '' || (vv.pay_real_price - 0) < 0){
                    err = 2
                }
            }
            if(vv.type == 1){
                if(vv.price_type != '' || vv.pay_name != '' || vv.pay_real_price != ''){
                    if(vv.price_type == ''){
                        err = 3
                    }
                    if(vv.pay_name == ''){
                        err = 4
                    }
                    if(vv.pay_real_price == '' || (vv.pay_real_price - 0) < 0){
                        err = 2
                    }
                }
            }
        })
        if(err == 2){
            return Message.error('实际金额不能为空或为负数')
        }else if(err == 3){
            return Message.error('请选择计费类型')
        }else if(err == 4){
            return Message.error('请输入收费项目')
        }else{
            objcetData.value.detail.map((v,i)=>{
                if(v.type == 1){
                    arr.push(v)
                }
            })
        }
        arr.map((v,i)=>{
            v.pay_price = v.pay_real_price
        })
        zhifuData.value.pay_dept_id = objcetData.value.pay_dept_id
        zhifuData.value.pay_items_json = arr
        request({
            url: 'financial/payOrder/save',
            method: 'post',
            data: zhifuData.value
        }).then(res => {
            zhifuShow.value = true
            payOrderId.value = res.data.id
            if(res.data.id){
                handleshoujuItem([res.data.id])
            }else if(res.data.ids){
                handleshoujuItem(res.data.ids)
            }
            
            getaccount()
            console.log('res:',res)
        })
        
        
    }
    const handleshoujuItem = (id)=>{
        request({
            url: 'financial/payOrder/index',
            method: 'get',
            params: {
                ids:id,
                prediction_id:[zhifuData.value.prediction_id],
            }
        }).then(res=>{
            console.log(res)
            let obj = JSON.parse(JSON.stringify(res.data.items[0]))
            obj.detail = []
            res.data.items.map((item)=>{
                obj.detail.push(...item.detail)
            })
            console.log("obj.detail:",obj.detail)
            let falgTrue = []
            obj.detail.map((item)=>{
                if(falgTrue.length == 0){
                    falgTrue.push(item) 
                }else{
                    let num = falgTrue.findIndex((ite)=>{
                    return ite.pay_name == item.pay_name
                })
                if(num == -1){
                    falgTrue.push(item) 
                }else{
                    falgTrue[num].pay_real_price = (falgTrue[num].pay_real_price - 0) + (item.pay_real_price - 0)
                }
                }
                
            })
            falgTrue.map((item)=>{
                item.pay_real_price = (item.pay_real_price - 0).toFixed(2)
            })
            obj.detail = falgTrue
            shoujuItem.value = obj
        })
            
    }
    const handelzhifuOk = async ()=>{ // 支付成功
        let obj = {}
        let ids = []
        itemList.value.map((v,i)=>{
            if(v.is_confirm == 1){
                ids.push(v.id)
            }
        })
        if(jiesuan.value == '1' || jiesuan.value == '2'){
            obj.pay_type = jiesuan.value == 1?'money':'periodic'
            obj.ids = payOrderId.value
            obj.pay_date = pay_date.value
        }
        if(jiesuan.value == '3'){
            obj.pay_type = 'now_pay'
            obj.ids = payOrderId.value
            obj.now_pay_type = zhifu.value
            obj.transfer_proof_images = fileList.value 
            obj.payment_method = zhifu.value
            obj.settlement_method = 1
            obj.pay_date = pay_date.value
            obj.notes = ''
            // obj.pay_order_id = this.zhifu_id    // 交易单号
            obj.dept_id = zhifuData.value.pay_dept_id    // 公司
            obj.opening_bank = opening_bank.value    // 开户行
            obj.account = account.value    // 收款账户
            obj.account_name = account_name.value    // 开户行名称
        }
        let res = await request({
            url: "financial/payOrder/pay",
            method: "post",
            data: obj,
        })
        if(res.code == 200){
            shoujuShow.value = true
            zhifuShow.value = false
            // emit("shuaxin")
            Message.success(res.message);
            
            return true
        }else{
            Message.error(res.message)
            return false
        }
        
    }
    const handleSelectPay_dept_id = (e)=>{
        objcetData.value.pay_dept_id = e
        handelavailableAmount(e)
    }
    const handelavailableAmount = (dept_id) =>{
        request({
            url: "financial/payOrder/deptList",
            method: "get",
            params: {
                page:1,
                pageSize:10,
                id:dept_id
            },
        }).then(resx =>{
            availableAmount.value = resx.data.items[0].money
        })
    }
    const handlechek = (index,rowIndex) =>{
        itemList.value[index].detail[rowIndex].is_confirm == 0?itemList.value[index].detail[rowIndex].is_confirm = 1:itemList.value[index].detail[rowIndex].is_confirm = 0
    }
    const  spanMethodAll= ({record,rowIndex, columnIndex}) => {
      if (rowIndex === record.weizhi - record.weizhizong && columnIndex === 0) {
        return {rowspan: record.weizhizong,colspan:1}
      }
    };
    const handleDeptList = () => {   //  获取公司列表
        request({
            url: 'system/dept/remote',
            method: 'post',
            data: {
            openPage: false,
            remoteOption: {
                filter: {
                type: ['=', 2],
                status: ['=',1]
                },
                select: ["id", "name"],
                sort: { id: "desc" }
            }
            }
        }).then(res => {
            res.data.map((v,i)=>{
                    v.keywords = [
                    v.name,
                    pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join(''),
                    pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
                    ]
            })
            dept_list.value = res.data
        })
    }
    

    const handleSOrt = (ceshiArr)=>{
        let arr = []           // 最终数据
        let linshiArr = []     //  未匹配的放数组里
        let linshititle = ''   // 临时变量
        ceshiArr.map((v,i)=>{
        if(i == 0){
            linshititle = v.name
            arr.push(v)
        }else{
            if(linshititle == v.name){
            arr.push(v)
            }else{
            linshiArr.push(v)
            }
        }
        })
        ceshiArr.map((v,i)=>{
        if(linshiArr.length != 0){
            linshiArr.map((vv,ii)=>{
            if(ii == 0){
                linshititle = linshiArr[0].name
                arr.push(linshiArr.shift())
            }else{
                if(linshititle == vv.name){
                arr.push(linshiArr.slice(ii,1))
                }
            }
            
            })
            
        }
        })
        arr.sort((a, b) => a.car_nos.localeCompare(b.car_nos));
        return arr
    }
    const handleWeizhi = (detail)=>{
        let carArr = []
        let carArrs = []
        detail.map((vv,ii)=>{
            carArr.push(vv.car_nos)
            carArrs.push({car_no:vv.car_nos,prediction_id:vv.prediction_id,billing_node:vv.billing_node})
        })
        var newArr = carArr.filter(function(item,index){  // 获取有多少车号
            return carArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个  
        });
        console.log('newArr',newArr)
        let numArr = []
        newArr.map((vv,ii)=>{
            let num = 0
            let name = ''
            carArrs.map((vvv,iii)=>{
                if(vv == vvv.car_no){
                    num++
                    name = vvv.car_no
                }
            })
            numArr.push({car_no:name,weizhi:num,weizhizong:num})
        })
        console.log('numArr',numArr)
        let weizhiArr = []
        let weizhinum = 0
        numArr.map((vv,ii)=>{
            weizhinum += vv.weizhi
            weizhiArr.push({car_no:vv.car_no,weizhi:weizhinum,weizhizong:vv.weizhizong,})
        })
        
        carArr = []
        detail.map((vv,ii)=>{
            carArr.push(vv.car_nos)
        })
        var newArr = carArr.filter(function(item,index){  // 获取有多少车号
            return carArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个  
        });
        numArr = []
        newArr.map((vv,ii)=>{
            let num = 0
            let name = ''
            carArr.map((vvv,iii)=>{
            if(vv == vvv){
                num++
                name = vvv
            }
            })
            numArr.push({car_no:name,weizhi:num,weizhizong:num})
        })
        weizhiArr = []
        weizhinum = 0
        numArr.map((vv,ii)=>{
            weizhinum += vv.weizhi
            weizhiArr.push({car_no:vv.car_no,weizhi:weizhinum,weizhizong:vv.weizhizong})
        })
        detail.map((vv,ii)=>{
            weizhiArr.map((vvv,iii)=>{
            if(vv.car_nos == vvv.car_no){
                vv.weizhi = vvv.weizhi
                vv.weizhizong = vvv.weizhizong
            }
            })
        })
        return detail
    }
    const handleAdd = (rowIndex,type)=>{
        console.log(rowIndex)
        let carArr = []
        if(type == 1){  // 新增
            let car_nos = objcetData.value.detail[rowIndex - 1].car_nos
            objcetData.value.detail.splice(rowIndex,0,{car_nos:car_nos,price_type:'',pay_name:'',pay_real_price:'',no_tax_price:'',tax_price:'',remark:'',type:1,caozuo:''})
        }else{  // 删除
            objcetData.value.detail.splice(rowIndex,1)
        }
        objcetData.value.detail.map((vv,ii)=>{
            carArr.push(vv.car_nos)
        })
        var newArr = carArr.filter(function(item,index){  // 获取有多少车号
            return carArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个  
        });
        let numArr = []
        newArr.map((vv,ii)=>{
            let num = 0
            let name = ''
            carArr.map((vvv,iii)=>{
            if(vv == vvv){
                num++
                name = vvv
            }
            })
            numArr.push({car_no:name,weizhi:num,weizhizong:num})
        })
        let weizhiArr = []
        let weizhinum = 0
        numArr.map((vv,ii)=>{
            weizhinum += vv.weizhi
            weizhiArr.push({car_no:vv.car_no,weizhi:weizhinum,weizhizong:vv.weizhizong})
        })
        objcetData.value.detail.map((vv,ii)=>{
            weizhiArr.map((vvv,iii)=>{
            if(vv.car_nos == vvv.car_no){
                vv.weizhi = vvv.weizhi
                vv.weizhizong = vvv.weizhizong
            }
            })
        })
    }
    const handletuhuanPriceType = (id)=>{
        let name = ''
        price_typeList.value.map((v,i)=>{
            if(v.key == id){
                name = v.title 
            }
        })
        return name
    }
    const handleZongPrice = (status) =>{
        let num = 0
        objcetData.value.detail.map((vv,ii)=>{
            if(vv.type == 1 && status == 1){
                if(vv.pay_price == ''){
                    num += 0
                }else{
                    num += (vv.pay_price - 0)
                }
                
            }
            if(vv.type == 1 && status == 2){
                if(vv.pay_real_price == ''){
                    num += 0
                }else{
                    num += (vv.pay_real_price - 0)
                }
            }
            if(vv.type == 1 && status == 3){
                if(vv.no_tax_price == ''){
                    num += 0
                }else{
                    num += (vv.no_tax_price - 0)
                }
            }
            if(vv.type == 1 && status == 4){
                if(vv.tax_price == ''){
                    num += 0
                }else{
                    num += (vv.tax_price - 0)
                }
            }
        })
        return num.toFixed(2)
    }
</script>

<style lang="less" scoped>
.zuidaBox{
    max-height: 700px;
    overflow: auto;
    scrollbar-width: none;
}
.zuidaBox::-webkit-scrollbar {
  display: none; /* 对于 Chrome, Safari 和 Opera */
}
.box{
    
    margin-bottom: 20px;
    &:last-child{
        margin-bottom:0;
    }
}
.chek{
    width: 14px;
    height: 14px;
    border-radius: 2px;
    border: 1px solid rgba(0, 0, 0, .15);
}
.act_chek{
    width: 14px;
    height: 14px;
    border-radius: 2px;
    border: 1px solid rgb(22, 93, 255);
    background: rgb(22, 93, 255);
}
</style>